package com.wrt.sps.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wrt.sps.entity.PageResults;
import com.wrt.sps.entity.Results;
import com.wrt.sps.mgt.entity.UploadFile;
import com.wrt.sps.mgt.entity.Writing;
import com.wrt.sps.web.service.UploadFileQueryService;
import com.wrt.sps.web.service.WritingQueryService;

import lombok.extern.log4j.Log4j2;

/**
 * 文章查询接口
 * 
 * @author 文瑞涛
 * @date 2021年1月4日 下午9:34:41
 */
@Controller
@RequestMapping("/web")
@Log4j2
public class WritingQueryController {

	@Resource
	private WritingQueryService writingQueryService;
	
	@Resource
	private UploadFileQueryService uploadFileQueryService;

	/**
	 * 
	 * 分页查询文章
	 * 
	 * @param 文章类型   type
	 * @param 当前页面   page
	 * @param 每页显示条数 limit
	 *
	 * @return 分页查询结果
	 */
	@GetMapping("/queryWriting")
	@ResponseBody
	public PageResults query(Writing.Type type, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int limit) {
		return new PageResults(writingQueryService.query(type, page - 1, limit));
	}

	/**
	 * 
	 * 查询文章详情
	 * 
	 * @param 文章主键 id
	 *
	 * @return 查询结果
	 */
	@GetMapping("/getDetails")
	@ResponseBody
	public Results getDetails(Long id) {
		Writing result = writingQueryService.getDetails(id);
		if (null != result) {
			return Results.success(null, result.getDetails());
		} else {
			return Results.fail(null, null);
		}
	}
	
	@GetMapping("/file/{code}")
	@ResponseBody
	public void file(@PathVariable("code")String code, HttpServletResponse response) {
		UploadFile uf = uploadFileQueryService.getUploadFile(code);
		if (null != uf) {
			File uploadfile = new File(uf.getPath());
			if (uploadfile.exists() && uploadfile.isFile()) {
				try (FileInputStream fis = new FileInputStream(uploadfile);
						BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
					byte[] bytes = new byte[1024];
					int len;
					while ((len = fis.read(bytes)) != -1) {
						response.getOutputStream().write(bytes, 0, len);
					}
					bos.flush();
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}
}
